package com.polaris.live.ui.backpack.fragment

import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterInside
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.PagConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.databinding.FragmentShoppingMallBinding
import com.polaris.live.interface_bag.ShoppingCallBack
import com.polaris.live.interface_bag.ShoppingMallCallBack
import com.polaris.live.popup.CommodityPopup
import com.polaris.live.popup.PreviewCommodityPopup
import com.polaris.live.resp.back_resp.PayerShopResp
import com.polaris.live.translation.R
import com.polaris.live.ui.main.activity.MainActivity
import com.polaris.live.utils.AppConfigUtils
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.backpack.ShoppingMallModel
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.bubble.DownLoadFileUtil.loadPag
import com.polaris.live.widget.tab.OnTabSelectListener
import com.polaris.live.widget.tab.TabBean
import org.libpag.PAGFile

/**
 * ShoppingMallFragment
 *
 * @author Created by 天晴 on 2024/7/16 16:23
 * @since 1.0.0
 **/
class ShoppingMallFragment : BaseVbFragment<ShoppingMallModel, FragmentShoppingMallBinding>(), ShoppingMallCallBack {

    private val mIsNeedBottom by lazy { arguments?.getBoolean("isNeedBottom", false) ?: true }

    private val mIsHome by lazy { arguments?.getBoolean("isHome", false) ?: false }

    //主页控制的字段，判断是否需要展示
    private var mHomeNeedShowPopup = true

    private val mFragments = ArrayList<Fragment>()

    private val mTitles = ArrayList<TabBean>()

    //上次点击的item
    private var mLastItem: PayerShopResp? = null

    private var mShoppingCallBack: ShoppingCallBack? = null

    private var mHidden = false

    private var mLastPosition = 0

    private val mDecorationNames by lazy {
        AppConfigUtils.getDecorationNames()
    }

    override fun initView(savedInstanceState: Bundle?) {
        initTitle()
        mBinding.previewLl.setOnSingleClickListener {
            mLastItem?.let { resp ->
                val url = when (resp.objectType) {
                    CommonConst.DressUp.LIVE_BROADCAST_ENTRY -> {
                        resp.ext
                    }

                    else -> {
                        resp.effectDisplayUrl
                    }
                }
                PreviewCommodityPopup.show(requireContext(), resp.objectType, url ?: resp.displayUrl)
            }
        }
        initListener()
    }

    private fun initListener() {
        // 添加回调来拦截返回事件
        if (mIsHome) {
            requireActivity().onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    // 在这里自定义返回事件的处理逻辑
                    if (mIsHome && lastPop != null && lastPop?.isShow == true) {
                        // 拦截返回手势，执行你想要的操作
                        dismissCommodityPopup()
                    } else {
                        // 如果不拦截，则调用默认的返回事件
                        isEnabled = false // 禁用当前拦截器并执行默认返回操作
                        requireActivity().onBackPressed()
                    }
                }
            })
        }
    }

    private fun onCreateCommodityFragment(type: Long): CommodityFragment {
        return CommodityFragment().apply {
            arguments = bundleOf(
                "type" to type
            )
            setShoppingMallCallBack(this@ShoppingMallFragment)
        }

    }

    private fun initTitle() {
        mTitles.add(
            TabBean(
                mDecorationNames?.get("${CommonConst.DressUp.AVATAR_FRAME}")
                    ?: StringUtils.getString(R.string.shopping_avatar)
            )
        )
        mFragments.add(onCreateCommodityFragment(CommonConst.DressUp.AVATAR_FRAME))
        mTitles.add(
            TabBean(
                mDecorationNames?.get("${CommonConst.DressUp.CHAT_BUBBLE}")
                    ?: StringUtils.getString(R.string.shopping_bubble)
            )
        )
        mFragments.add(onCreateCommodityFragment(CommonConst.DressUp.CHAT_BUBBLE))
        mTitles.add(
            TabBean(
                mDecorationNames?.get("${CommonConst.DressUp.LIVE_BROADCAST_ENTRY}")
                    ?: StringUtils.getString(R.string.shopping_car)
            )
        )
        mFragments.add(onCreateCommodityFragment(CommonConst.DressUp.LIVE_BROADCAST_ENTRY))
        mTitles.add(
            TabBean(
                mDecorationNames?.get("${CommonConst.DressUp.USER_PROFILE}")
                    ?: StringUtils.getString(R.string.shopping_info_card)
            )
        )
        mFragments.add(onCreateCommodityFragment(CommonConst.DressUp.USER_PROFILE))
        mTitles.add(
            TabBean(
                mDecorationNames?.get("${CommonConst.DressUp.HOMEPAGE_BACKGROUND}")
                    ?: StringUtils.getString(R.string.shopping_floating)
            )
        )
        mFragments.add(onCreateCommodityFragment(CommonConst.DressUp.HOMEPAGE_BACKGROUND))
        mTitles.add(
            TabBean(
                mDecorationNames?.get("${CommonConst.DressUp.LIVE_EFFECT}")
                    ?: StringUtils.getString(R.string.shopping_entrance)
            )
        )
        mFragments.add(onCreateCommodityFragment(CommonConst.DressUp.LIVE_EFFECT))
        mTitles.add(
            TabBean(
                mDecorationNames?.get("${CommonConst.DressUp.PARTY_BACKGROUND}")
                    ?: StringUtils.getString(R.string.shopping_background)
            )
        )
        mFragments.add(onCreateCommodityFragment(CommonConst.DressUp.PARTY_BACKGROUND))
        mTitles.add(
            TabBean(
                mDecorationNames?.get("${CommonConst.DressUp.SOUND_EFFECT}")
                    ?: StringUtils.getString(R.string.voice_sound)
            )
        )
        mFragments.add(onCreateCommodityFragment(CommonConst.DressUp.SOUND_EFFECT))

        mBinding.inContent.viewpager2.adapter = ViewPagerAdapter(mFragments, this)
        mBinding.inContent.tab.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                mBinding.inContent.viewpager2.currentItem = position
            }

            override fun onTabReselect(position: Int) {
            }
        })

        mBinding.inContent.viewpager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (mLastPosition == position) {
                    return
                }
                val lastOrNull = mFragments.getOrNull(mLastPosition) ?: return
                if (lastOrNull is CommodityFragment) {
                    lastOrNull.onHiddenChanged(true)
                }
                val orNull = mFragments.getOrNull(position) ?: return
                if (orNull is CommodityFragment) {
                    orNull.onHiddenChanged(false)
                    orNull.show()
                    mLastPosition = position
                }
            }
        })
        mBinding.inContent.viewpager2.offscreenPageLimit = mFragments.size
        mBinding.inContent.tab.setViewPage(mBinding.inContent.viewpager2)
        mBinding.inContent.tab.setTabs(mTitles, mBinding.inContent.svScroll)
        mBinding.inContent.viewpager2.currentItem = 0
    }

    fun goIndex(type: Long) {
        when (type) {
            CommonConst.DressUp.AVATAR_FRAME -> {
                mBinding.inContent.viewpager2.currentItem = 0
                mBinding.inContent.tab.onPageSelected(0)
            }

            CommonConst.DressUp.CHAT_BUBBLE -> {
                mBinding.inContent.viewpager2.currentItem = 1
                mBinding.inContent.tab.onPageSelected(1)
            }

            CommonConst.DressUp.LIVE_BROADCAST_ENTRY -> {
                mBinding.inContent.viewpager2.currentItem = 2
                mBinding.inContent.tab.onPageSelected(2)
            }

            CommonConst.DressUp.USER_PROFILE -> {
                mBinding.inContent.viewpager2.currentItem = 3
                mBinding.inContent.tab.onPageSelected(3)
            }

            CommonConst.DressUp.HOMEPAGE_BACKGROUND -> {
                mBinding.inContent.viewpager2.currentItem = 4
                mBinding.inContent.tab.onPageSelected(4)
            }

            CommonConst.DressUp.LIVE_EFFECT -> {
                mBinding.inContent.viewpager2.currentItem = 5
                mBinding.inContent.tab.onPageSelected(5)
            }

            CommonConst.DressUp.PARTY_BACKGROUND -> {
                mBinding.inContent.viewpager2.currentItem = 6
                mBinding.inContent.tab.onPageSelected(6)
            }

            CommonConst.DressUp.SOUND_EFFECT -> {
                mBinding.inContent.viewpager2.currentItem = 7
                mBinding.inContent.tab.onPageSelected(7)
            }
        }
    }

    private var lastPop: CommodityPopup? = null
    private var lastItem: PayerShopResp? = null
    private fun showCommodityPopup(
        item: PayerShopResp,
    ) {
        if (lastPop != null && lastPop?.isShow == true) {
            if (mIsHome) {
                if (lastItem?.shopId == item.shopId) {
                    dismissCommodityPopup()
                } else {
                    lastPop?.upData(item)
                }
            } else {
                lastPop?.upData(item)
            }
            lastItem = item
            return
        }
        lastItem = item
        lastPop = CommodityPopup(requireContext(), mViewModel, item, mIsNeedBottom, onShow = {
            mBinding.pagView.isClickable = it
        }, mBuySuccess = { type ->
            buySuccess(type)
        }) { type ->
            //如果是MainActivity就代表是主页的fragment了
            if (requireActivity() is MainActivity) {
                Router.builder(RoutePath.BACKPACK_ACTIVITY)
                    .withInt("index", 0)
                    .withLong("decorationType", type)
                    .navigation(requireActivity())
            } else {
                mShoppingCallBack?.toLook(type)
            }
        }
        XPopup.Builder(requireContext())
            .isViewMode(true)
            .moveUpToKeyboard(false)
            .hasShadowBg(false)
            .enableDrag(false)
            .isClickThrough(true)
            .isTouchThrough(true)
            .customHostLifecycle(lifecycle)
            .setPopupCallback(object : SimpleCallback() {
                override fun onBackPressed(popupView: BasePopupView?): Boolean {
                    if (!mIsHome) {
                        requireActivity().finish()
                        return false
                    }
                    return false
                }

            })
            .dismissOnBackPressed(true)
            .dismissOnTouchOutside(false)
            .asCustom(lastPop)
            .show()
    }

    private fun dismissCommodityPopup() {
        lastPop?.dismiss()
        lastPop = null
    }

    override fun onSelectCallback(item: PayerShopResp?) {
        mBinding.cosHead.visibility = View.GONE
        mBinding.avFv.visibility = View.GONE
        mBinding.cosProfile.visibility = View.GONE
        mBinding.chatIcon.visibility = View.GONE
        mBinding.cosScreen.visibility = View.GONE
        mBinding.frameAvatar.visibility = View.GONE
        mBinding.framePag.visibility = View.GONE
        mBinding.frameBack.visibility = View.GONE
        mBinding.screenPag.visibility = View.GONE
        mBinding.screenBack.visibility = View.GONE
        mBinding.effectIcon.visibility = View.GONE
        mBinding.profilePag.visibility = View.GONE
        mBinding.profileBack.visibility = View.GONE
        mBinding.previewLl.visibility = View.INVISIBLE
        mBinding.entryScreenItemview.visibility = View.GONE
        if (item == null) {
            dismissCommodityPopup()
            return
        }
        mLastItem = item
        if (!mHidden && mHomeNeedShowPopup) {
            showCommodityPopup(item)
        }

        when (item.objectType) {
            CommonConst.DressUp.AVATAR_FRAME -> {
                val effectDisplayUrl = item.effectDisplayUrl
                if (effectDisplayUrl != null && effectDisplayUrl.contains(".pag?")) {
                    mBinding.avFv.visibility = View.VISIBLE
                    mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(item.effectDisplayUrl))
                    mBinding.avHead.setImageUrl(UserManager.getUser().avatar)
                } else if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
                    mBinding.framePag.composition = PAGFile.Load("")
                    loadPag(lifecycleScope, effectDisplayUrl) { pagPath, _ ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()
                        ) {
                            showFramePag(item)
                        }
                    }
                } else {
                    showFrameImage(item)
                }

            }

            CommonConst.DressUp.USER_PROFILE -> {
                mBinding.profileAvatar.setImageUrl(UserManager.getUser().avatar)
                mBinding.cosProfile.visibility = View.VISIBLE
                if (item.effectDisplayUrl != null && item.effectDisplayUrl.endsWith(PagConst.PAG)) {
                    loadPag(lifecycleScope, item.effectDisplayUrl) { pagPath, localPath ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                            mBinding.profilePag.visibility = View.VISIBLE
                            mBinding.profilePag.apply {
                                setRepeatCount(-1)
                                composition = PAGFile.Load(localPath)
                                if (!isPlaying) {
                                    play()
                                }
                            }
                        }
                    }
                } else {
                    mBinding.profileBack.visibility = View.VISIBLE
                    Glide.with(mBinding.profileBack).load(effectIsNull(item)).into(mBinding.profileBack)
                }
            }

            CommonConst.DressUp.CHAT_BUBBLE -> {
                mBinding.chatIcon.visibility = View.VISIBLE
                Glide.with(mBinding.chatIcon).load(effectIsNull(item)).into(mBinding.chatIcon)
            }

            CommonConst.DressUp.LIVE_EFFECT -> {
                mBinding.previewLl.visibility = View.VISIBLE
                val effectDisplayUrl = item.effectDisplayUrl
                if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
                    loadPag(lifecycleScope, effectDisplayUrl) { pagPath, _ ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                            mBinding.entryScreenItemview.visibility = View.VISIBLE
                            mBinding.entryScreenItemview.setData(item.effectDisplayUrl)
                        }
                    }
                } else {
                    mBinding.entryScreenItemview.visibility = View.VISIBLE
                    mBinding.entryScreenItemview.setData(item.effectDisplayUrl ?: item.displayUrl)
                }
            }

            CommonConst.DressUp.LIVE_BROADCAST_ENTRY -> {
                mBinding.previewLl.visibility = View.VISIBLE
                mBinding.cosScreen.visibility = View.VISIBLE
                mBinding.screenPag.composition = PAGFile.Load("")

                val effectDisplayUrl = item.effectDisplayUrl
                if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
                    loadPag(lifecycleScope, effectDisplayUrl) { pagPath, _ ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                            showScreenPag(item)
                        }
                    }
                } else {
                    mBinding.screenBack.visibility = View.VISIBLE
                    Glide.with(mBinding.screenBack).load(effectIsNull(item))
                        .into(mBinding.screenBack)
                }

            }

            CommonConst.DressUp.HOMEPAGE_BACKGROUND -> {
                mBinding.previewLl.visibility = View.VISIBLE
                mBinding.cosScreen.visibility = View.VISIBLE
                mBinding.screenBack.visibility = View.VISIBLE
                Glide.with(mBinding.screenBack)
                    .load(ImageUtils.imgPath(item.displayUrl))
                    .into(mBinding.screenBack)
            }

            CommonConst.DressUp.PARTY_BACKGROUND -> {
                mBinding.previewLl.visibility = View.VISIBLE
                mBinding.cosScreen.visibility = View.VISIBLE
                mBinding.screenBack.visibility = View.VISIBLE
                Glide.with(mBinding.screenBack)
                    .load(ImageUtils.imgPath(item.displayUrl))
                    .apply(RequestOptions().transform(CenterInside(), RoundedCorners(4.autoDp)))
                    .into(mBinding.screenBack)
            }

            CommonConst.DressUp.SOUND_EFFECT -> {
                mBinding.previewLl.visibility = View.VISIBLE
                mBinding.cosScreen.visibility = View.VISIBLE
                mBinding.screenPag.composition = PAGFile.Load("")

                val effectDisplayUrl = item.effectDisplayUrl
                if (effectDisplayUrl != null && effectDisplayUrl.endsWith(PagConst.PAG)) {
                    loadPag(lifecycleScope, effectDisplayUrl) { pagPath, _ ->
                        if (pagPath == mLastItem?.effectDisplayUrl && !isDestroyView()) {
                            showScreenPag(item)
                        }
                    }
                } else {
                    mBinding.screenBack.visibility = View.VISIBLE
                    Glide.with(mBinding.screenBack).load(effectIsNull(item))
                        .into(mBinding.screenBack)
                }
            }
        }

    }

    override fun buySuccess(type: Long) {
        mShoppingCallBack?.buySuccess(type)
    }

    //判断预览图是否为空
    private fun effectIsNull(item: PayerShopResp): String {
        return if (item.effectDisplayUrl != null) {
            ImageUtils.imgPath(item.effectDisplayUrl)
        } else {
            ImageUtils.imgPath(item.displayUrl)
        }
    }

    //展示头像框 图片形式
    private fun showFrameImage(item: PayerShopResp) {
        mBinding.cosHead.visibility = View.VISIBLE
        mBinding.frameAvatar.visibility = View.VISIBLE
        mBinding.frameBack.visibility = View.VISIBLE
        mBinding.frameAvatar.setImageUrl(UserManager.getUser().avatar)
        Glide.with(mBinding.frameBack).load(effectIsNull(item))
            .into(mBinding.frameBack)
    }

    //展示头像框 pag形式
    private fun showFramePag(item: PayerShopResp) {
        mBinding.cosHead.visibility = View.VISIBLE
        mBinding.frameAvatar.visibility = View.VISIBLE
        mBinding.frameAvatar.setImageUrl(UserManager.getUser().avatar)
        val path =
            item.effectDisplayUrl?.let { FileUtils.getFilePath(FileUtils.getPagFile(), it) }
        mBinding.framePag.visibility = View.VISIBLE
        mBinding.framePag.apply {
            composition = PAGFile.Load(path)
            setRepeatCount(-1)
            if (!isPlaying) {
                play()
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        mHidden = hidden
        if (!hidden && mHomeNeedShowPopup) {
            mLastItem?.let {
                showCommodityPopup(it)
            }
            withLoaded {
                val fragment = mFragments.getOrNull(mBinding.inContent.viewpager2.currentItem)
                mLastPosition = mBinding.inContent.viewpager2.currentItem
                if (fragment != null && fragment is CommodityFragment) {
                    fragment.onHiddenChanged(mHidden)
                    fragment.show()
                }
            }
        } else {
            dismissCommodityPopup()
        }
    }

    fun setHomeNeedShow(isShow: Boolean) {
        if (isCreated()) {
            mHomeNeedShowPopup = isShow
        }
    }

    fun setOnShoppingCallBack(l: ShoppingCallBack) {
        mShoppingCallBack = l
    }

    //展示座驾pag
    private fun showScreenPag(item: PayerShopResp) {
        val path =
            item.effectDisplayUrl?.let { FileUtils.getFilePath(FileUtils.getPagFile(), it) }
        mBinding.screenPag.visibility = View.VISIBLE
        mBinding.screenPag.apply {
            composition = PAGFile.Load(path)
            if (!isPlaying) {
                play()
            }
        }
        mBinding.screenPag.apply {
            composition = PAGFile.Load(path)
            setRepeatCount(1)
            if (!isPlaying) {
                play()
            }
        }
    }

}